package com.ruoyi.common.utils.http;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

/**
 * 通用http发送方法
 * 
 * @author ruoyi
 */
public class HttpUtils
{
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    private final static PoolingHttpClientConnectionManager poolConnManager = new PoolingHttpClientConnectionManager();

    private final static HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
        //retry handler
        public boolean retryRequest(IOException exception, int executionCount,
                HttpContext context) {
            if (executionCount >= 3) {
                return false;
            }

            if (exception instanceof NoHttpResponseException) {
                return true;
            }

            if (exception instanceof InterruptedIOException) {
                return false;
            }

            if (exception instanceof UnknownHostException) {
                return false;
            }

            if (exception instanceof ConnectTimeoutException) {
                return false;
            }

            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }

    };


        public static int timeout = 60000;


    // 优化连接池配置
    static {
        poolConnManager.setMaxTotal(300); // 提高最大连接数以支持更高并发
        poolConnManager.setDefaultMaxPerRoute(50); // 增加每个路由的最大连接数
        poolConnManager.setValidateAfterInactivity(500); // 进一步缩短连接验证间隔
    }

    // 修改连接池配置（添加定期检查）
    private static final CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(poolConnManager)
            .evictExpiredConnections()
            .evictIdleConnections(5, TimeUnit.SECONDS) // 缩短空闲连接清理周期
            .setConnectionManagerShared(true) // 共享连接池
            .setRetryHandler(httpRequestRetryHandler)
            .build();

    // 提取通用请求配置方法
    private static RequestConfig createRequestConfig(int timeout) {
        return RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(2000)
                .setSocketTimeout(timeout)
                .build();
    }



    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url)
    {
        return sendGet(url, StringUtils.EMPTY);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param)
    {
        return sendGet(url, param, Constants.UTF8);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String contentType)
    {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param)
    {
        return sendPost(url, param, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url 发送请求的 URL
     * @param param 请求参数
     * @param contentType 内容类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, String contentType)
    {
        Map<String, String> headers = new HashMap();
        headers.put("Content-Type", contentType);
        return sendPost(url, param, headers, 60000);
    }


    /**
     *
     * @param url
     * @param param
     * @param contentType
     * @param requestionConut  请求次数（含重试）
     * @return
     */
    public static String sendPost(String url, String param, String contentType, int requestionConut)
    {
        Map<String, String> headers = new HashMap();
        headers.put("Content-Type", contentType);
        return sendPost(url, param, headers, requestionConut, 60000);
    }


    public static String sendPost(String url, String jsonString, Map<String, String> headers,
            int requestionConut, Integer timeoutP) {
        log.info("sendPost url = {}, retryCount = {}", url, requestionConut);
        requestionConut--;
        CloseableHttpResponse response = null;
        String result = null;
        try {
            long start = System.currentTimeMillis();

            HttpPost httpPost = new HttpPost(url);
            setHeaders(httpPost, headers);

            int t = timeoutP == null || timeoutP <= 0 ? timeout : timeoutP;
            httpPost.setConfig(createRequestConfig(t));

            StringEntity paramEntity = new StringEntity(jsonString, StandardCharsets.UTF_8);
            paramEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(paramEntity);

            response = httpClient.execute(httpPost);
            result = handleResponse(response, url);

            logRequestSuccess(url, System.currentTimeMillis() - start);
        } catch (SocketTimeoutException | HttpHostConnectException | NoHttpResponseException |
                 ConnectTimeoutException e) {
            log.error("Connection error for URL: {}", url, e);
            if (requestionConut > 0) {
                sleepBeforeRetry();
                return sendPost(url, jsonString, headers, requestionConut, timeoutP);
            } else {
                return "{\"code\":\"504\",\"msg\":\"请求超时\",\"responseCode\":\"504\",\"responseMsg\":\"请求超时\"}";
            }
        } catch (Exception e) {
            log.error("sendPost Exception for URL: {}, param: {}", url, jsonString, e);
        } finally {
            closeResponse(response);
        }
        return result;
    }

    /*
     * 优化设置请求头方法
     * @param httpRequest
     * @param headers
     */
    private static void setHeaders(HttpRequest httpRequest, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpRequest.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /*
     * 提取响应处理逻辑
     * @param response
     * @param url
     * @return
     * @throws IOException
     */
    private static String handleResponse(CloseableHttpResponse response, String url)
            throws IOException {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.error("[HTTP Request Failed] URL={}, StatusCode={}, Response={}", url,
                    statusLine.getStatusCode(), responseBody);
            if (statusLine.getStatusCode() == 422) {
                try{
                    JSONObject json = JSONObject.parseObject(responseBody);
                    JSONArray array = json.getJSONArray("detail");
                    StringBuilder string = new StringBuilder();
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        if (i == 0) {
                            string.append(j.getString("msg")).append("__");
                        } else {
                            string.append("--");
                        }
                        string.append(j.getJSONArray("loc").toString().replace("\"body\"", "")
                                .replace("\"", "").replace(",", ""));
                    }

                    return String.format("{\"statusCode\":%s,\"msg\":\"%s\"}", statusLine.getStatusCode(), string.toString());
                } catch (Exception e) {
                    log.error("handleResponse error " , e);
                }
                return responseBody;
            }

            return null;
        }
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }


    /**
     *  提取日志记录逻辑
     * @param url
     * @param costTime
     */
    private static void logRequestSuccess(String url, long costTime) {
        log.info("Request success, URL={}, CostTime={}ms", url, costTime);
    }

    private static void closeResponse(CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.warn("Failed to close response", e);
            }
        }
    }


    /**
     * 提取重试间隔逻辑
     */
    private static void sleepBeforeRetry() {
        try {
            Thread.sleep(30000); // 增加重试间隔
        } catch (InterruptedException ignored) {
            Thread.currentThread().interrupt(); // 恢复中断状态
        }
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 		发送请求的 URL
     * @param param 	请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param headers 	请求头
     * @param timeout 	超时时间
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, Map<String, String> headers,
            Integer timeout) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            // 遍历设置自定义请求头
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            conn.setReadTimeout(timeout);
            conn.setConnectTimeout(5000);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            if (StringUtils.length(result) < 1500) {
                log.info("recv - {}", result);
            }
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error(
                    "调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param,
                    e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url, String param)
    {
        return sendSSLPost(url, param, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    }

    public static String sendSSLPost(String url, String param, String contentType)
    {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try
        {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", contentType);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null)
            {
                if (ret != null && !"".equals(ret.trim()))
                {
                    result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();
    }

    private static class TrustAnyTrustManager implements X509TrustManager
    {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers()
        {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            return true;
        }
    }
}